package com.mayuanfei.springboot15.controller;

import cn.hutool.json.JSONUtil;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastJsonValue;
import com.hazelcast.map.IMap;
import com.mayuanfei.springboot15.common.Constants;
import com.mayuanfei.springboot15.pojo.UserInfo2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * Hazelcast的HazelcastJsonValue序列化器
 *
 * @author 老马
 * @date 2023-07-24 14:01
 */
@RestController
public class JsonValueController {
    @Resource
    private HazelcastInstance hazelcastInstance;

    @PostMapping(value = "/writeJsonValue")
    public UserInfo2 writeDataToHazelcast(String userId, String userName, Integer age) {
        UserInfo2 userInfo = new UserInfo2();
        userInfo.setUserId(userId);
        userInfo.setUserName(userName);
        userInfo.setAge(age);
        userInfo.setBirthday(LocalDate.now());
        userInfo.setAddress("北京");
        IMap<String, Object> map = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
        map.put(userId, new HazelcastJsonValue(JSONUtil.toJsonStr(userInfo)));
        return userInfo;
    }

    @GetMapping(value = "/readOneJsonValue")
    public UserInfo2 readDataFromHazelcast(String userId) {
        IMap<String, Object> map = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
         String userInfoJson = map.get(userId).toString();
         return JSONUtil.toBean(userInfoJson, UserInfo2.class);
    }
}